﻿using dotnet2cache.Abstractions;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Text;

namespace dotnet2cache.Memory
{
    public class Level1CacheProvider : ILevel1CacheProvider
    {
        private MemoryCache _memoryCache;
        private MemoryCacheOptions _memoryCacheOptions;

        public Level1CacheProvider(MemoryCacheOptions memoryCacheOptions)
        {
            _memoryCacheOptions = memoryCacheOptions;
            _memoryCache = new MemoryCache(memoryCacheOptions);
        }

        public CacheValue<T> Get<T>(string key)
        {
            var vaule = _memoryCache.Get<T>(key);
            if(vaule==null)
            {
                return new CacheValue<T>();
            }

            return new CacheValue<T>(vaule);
        }

        public bool IsExist(string key)
        {
            return _memoryCache.TryGetValue(key, out object o);
        }

        public bool Remove(string key)
        {
            _memoryCache.Remove(key);
            return true;
        }

        public void Set<T>(string key, CacheValue<T> value, CacheOptionEntry cacheOptionEntry)
        {
            if(value.HaveValue)
            {
                _memoryCache.Set<T>(key, value.Value, CreateCaheEntryOptions(cacheOptionEntry));
            }
           
        }

        private MemoryCacheEntryOptions CreateCaheEntryOptions(CacheOptionEntry cacheOptionEntry)
        {
            var option = new MemoryCacheEntryOptions();
            if (_memoryCacheOptions.SizeLimit.HasValue && _memoryCacheOptions.SizeLimit > 0)
            {
                option.SetSize(cacheOptionEntry.Size.HasValue ? cacheOptionEntry.Size.Value : 1);
            }
            if(cacheOptionEntry.AbsoluteExpiration.HasValue)
            {
                option.SetAbsoluteExpiration(cacheOptionEntry.AbsoluteExpiration.Value);
            }


            return option;
        }
    }
}
